#!/usr/bin/env python
# -*- encoding: utf-8 -*-

import pandas as pd

from xpy3lib.XRetryableQuery import XRetryableQuery
from xpy3lib.XRetryableSave import XRetryableSave
from sicost.AbstractDPJob import AbstractDPJob
from sicost.dp_common_job import DP011MJob__df7


class DP011_L_Job(AbstractDPJob):
    """
    获取消耗信息 按照类型调用不同存储过程

    SU_AJBG_DP0102 主原料
    BPC 能耗
    BPC 锌耗

    从main函数传入参数
    p_account,p_cost_center,p_unit,p_account_period_start,p_account_period_end,p_data_type
    """

    cost_center_org = None
    data_type = None

    # NOTE p_wce_org =v_wce,
    # NOTE p_wce=LEFT(v_wce,1)||'@@@@'
    wce_org = None
    wce = None

    cal_type = None
    coef = None
    mon = None

    def __init__(self,
                 p_config=None,
                 p_db_conn_mpp=None,
                 p_db_conn_rds=None,
                 p_db_conn_dbprod7=None,
                 p_unit=None,
                 p_account=None,
                 p_cost_center_org=None,
                 p_cost_center=None,
                 p_account_period_start=None,
                 p_account_period_end=None,
                 p_data_type=None,
                 p_wce_org=None,
                 p_wce=None,
                 p_cal_type=None,
                 p_coef=None,
                 p_mon=None,p_df7=None):
        """

        :param p_config:
        :param p_db_conn_mpp:
        :param p_db_conn_rds:
        :param p_db_conn_dbprod7:
        :param p_unit:
        :param p_account:
        :param p_cost_center_org:
        :param p_cost_center:
        :param p_account_period_start:
        :param p_account_period_end:
        :param p_data_type: data type是 0 D M。分别是 实时、每日、每月
        :param p_wce_org: 成本科目编号
        :param p_wce:
        :param p_cal_type:
        :param p_coef:
        :param p_mon:
        """
        super(DP011_L_Job, self).__init__(p_config=p_config,
                                          p_db_conn_mpp=p_db_conn_mpp,
                                          p_db_conn_rds=p_db_conn_rds,
                                          p_db_conn_dbprod7=p_db_conn_dbprod7,
                                          p_unit=p_unit,
                                          p_account=p_account,
                                          p_cost_center=p_cost_center,
                                          p_account_period_start=p_account_period_start,
                                          p_account_period_end=p_account_period_end)
        self.cost_center_org = p_cost_center_org
        self.data_type = p_data_type
        self.wce_org = p_wce_org
        self.wce = p_wce
        self.cal_type = p_cal_type
        self.coef = p_coef
        self.mon = p_mon
        self.df7 = p_df7

    def do_execute(self):
        """
        """
        self.logger.info('DP011_L_Job.do_execute')
        self.__step_1()

        super(DP011_L_Job, self).do_execute()

    def __step_1(self):
        # df7 = DP011MJob__df7(db_conn_dbprod7=self.db_conn_dbprod7, db_conn_rds=self.db_conn_rds,
        #                      wce_org=self.wce_org,
        #                      data_type=self.data_type,
        #                      account=self.account,
        #                      cost_center_org=self.cost_center_org,
        #                      unit=self.unit,
        #                      account_period_start=self.account_period_start,
        #                      account_period_end=self.account_period_end)
        df7L = self.df7

        def __cal_WORK_DATE(x):
            rst = x.WORK_TIME[0:4]
            return rst

        df7L['WORK_DATE'] = df7L.apply(lambda x: __cal_WORK_DATE(x), axis=1)


        sql = " SELECT " \
              " UNITCONSUME AS CONSUME," \
              " COST_CENTER," \
              " ACCT AS ACCOUNT," \
              " DATE AS WORK_DATE" \
              " FROM BGTAMAS1.T_ADS_WH_SICB_DP0101" \
              " WHERE 1=1 " \
              " AND COST_SUBJECT = '%s'" % (self.wce_org)
        self.logger.info(sql)
        # df = XRetryableQuery(p_db_conn=self.db_conn_dbprod7, p_sql=sql, p_max_times=5).redo()
        df = XRetryableQuery(p_db_conn=self.db_conn_mpp, p_sql=sql, p_max_times=5).redo()
        df.columns = df.columns.str.upper()
        self.logger.info(df)
        success = df.empty is False
        df2 = df

        # df7 merge df2 left on COST_CENTER,ACCOUNT,DATA_TYPE,WORK_DATE 得到df3
        df3 = pd.merge(df7L, df2, on=['COST_CENTER', 'ACCOUNT',  'WORK_DATE'], how='left')
        df3.drop(['WORK_DATE'], axis=1, inplace=True)
        df7L.drop(['WORK_DATE'], axis=1, inplace=True)

        def __cal_ACT_N(x):
            rst = 0
            if x.CONSUME == 0:
                rst = 0
            else:
                rst = x.CONSUME * x.ACT_WT
            return rst

        df3['ACT_N'] = df3.apply(lambda x: __cal_ACT_N(x), axis=1)

        def __cal_CONSUME_N(x):
            rst = 0
            if x.CONSUME == 0:
                rst = 0
            else:
                rst = x.CONSUME * x.ACT_WT
            return rst

        df3['CONSUME_N'] = df3.apply(lambda x: __cal_CONSUME_N(x), axis=1)

        df3.drop(['REC_ID'], axis=1, inplace=True)
        df3['REC_CREATOR'] = df3['REC_REVISOR']
        df3['REC_CREATE_TIME'] = df3['REC_REVISOR_TIME']
        df3.rename(columns={'ACCOUNT': 'ACCT'}, inplace=True)
        df3.rename(columns={'FACTORY': 'DEPARTMENT_CODE'}, inplace=True)
        df3.rename(columns={'UNIT': 'UNIT_CODE'}, inplace=True)
        df3.rename(columns={'TEAM': 'CLASS'}, inplace=True)
        df3.rename(columns={'WORK_TIME': 'PRODUCE_TIME'}, inplace=True)
        df3.rename(columns={'PROCESS_START_TIME': 'PRODUCE_START_TIME'}, inplace=True)
        df3.rename(columns={'PROCESS_END_TIME': 'PRODUCE_END_TIME'}, inplace=True)
        df3.rename(columns={'PRODUCT_CODE': 'BYPRODUCT_CODE'}, inplace=True)
        df3.rename(columns={'ST_NO': 'STEELNO'}, inplace=True)
        df3.rename(columns={'MAT_NO': 'PROD_COILNO'}, inplace=True)
        df3.rename(columns={'IN_PRODUCT_CODE': 'INPUT_BYPRODUCT_CODE'}, inplace=True)
        df3.rename(columns={'IN_MAT_NO': 'ENTRY_COILNO'}, inplace=True)
        df3.rename(columns={'WT': 'OUTPUT_WT'}, inplace=True)
        df3.rename(columns={'ACT_WT': 'ACT_OUTPUT_WT'}, inplace=True)
        df3.rename(columns={'IN_WT': 'INPUT_WT'}, inplace=True)
        df3.rename(columns={'ACT_IN_WT': 'ACT_INPUT_WT'}, inplace=True)
        df3.rename(columns={'WCE': 'COST_SUBJECT'}, inplace=True)
        df3.rename(columns={'ACT_N': 'COST_SUBJECT_ON_AMT'}, inplace=True)
        df3.rename(columns={'CONSUME': 'UNITCONSUME'}, inplace=True)
        df3.rename(columns={'CONSUME_ITEM': 'CONSUME_PROJ'}, inplace=True)
        df3.rename(columns={'CONSUME_DESC': 'CONSUME_PROJ_DESC'}, inplace=True)
        df3.rename(columns={'CONSUME_UNIT': 'CONSUME_PROJ_UNIT'}, inplace=True)
        df3.rename(columns={'CONSUME_N': 'CONSUME_AMT'}, inplace=True)
        df3.rename(columns={'APP_THROW_AI_MODE': 'APPTHROWAIMODE'}, inplace=True)
        df3.rename(columns={'DESIGN_ANNEAL_DIAGRAM_CODE': 'ANNEAL_CURVE'}, inplace=True)
        df3.rename(columns={'IN_MAT_WIDTH': 'ENTRY_MAT_WIDTH'}, inplace=True)
        df3.rename(columns={'IN_MAT_THICK': 'ENTRY_MAT_THICK'}, inplace=True)
        df3.rename(columns={'TRIM_WIDTH': 'TRIMM_WIDTH'}, inplace=True)
        df3.rename(columns={'IN_MAT_INNER_DIA': 'ENTRY_MAT_INDIA'}, inplace=True)
        df3.rename(columns={'PICKL_TRIM_FLAG': 'PICKLING_TRIMMING_FLAG'}, inplace=True)
        df3.rename(columns={'LAYER_TYPE': 'COATING_TYPE'}, inplace=True)
        df3.rename(columns={'TOP_COAT_WT': 'TOP_COATING_WT'}, inplace=True)
        df3.rename(columns={'BOT_COAT_WT': 'BOT_COATING_WT'}, inplace=True)
        df3.rename(columns={'LAS_NOTCH_FLAG': 'PRODUCE_NICK_FLAG'}, inplace=True)

        # 将df3插入到BGRAGGCB.SU_AJBG_DP0101
        XRetryableSave(p_db_conn=self.db_conn_rds, p_table_name='T_ADS_FACT_SICB_DP0103', p_schema='BGTARAS1',
                       p_dataframe=df3,
                       p_max_times=5).redo()